﻿@{
    ViewBag.Title = "Users";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<table id="marbleTable" class="stripe row-border order-column" style="width: 100%">
    <thead>
        <th>Id</th>
        <th>Edit</th>
        <th>Name</th>
        <th>Role</th>
        <th>Email</th>
        <th>LoginId</th>
        <th>Password</th>
        <th>Status</th>
        <th>POSCounter</th>
        <th>Department</th>
        <th>Manager</th>
        <th>CompanyAdmin</th>
        <th>EmpStartDate</th>
        <th>EmpEndDate</th>
        <th>EmpEndResone</th>
        <th>PasswordChangeDate</th>
        <th>Invalid Attempts</th>
        <th>LastLoginTime</th>
        <th>LastLogoutTime</th>
        <th>CreationDate</th>
        <th>CreatedBy</th>
        <th>LastUpdatedBy</th>
        <th>LastUpdatedDate</th>
    </thead>
    @foreach (var item in ViewBag.users)
    {  
        <tr>
            <td>
                <lable class="fixedCol1">@(item.Id == 0 ? "" : item.Id) </lable>
            </td>
            <td>
                <a class="edit" title="Edit" data-toggle="tooltip" onclick="EditUser('@item.Id')">
                    <i class="material-icons" style="cursor: pointer;">&#xE254;</i>
                </a>
                <a class="delete" title="Delete" data-toggle="tooltip" onclick="DeleteUser('@item.Id')">
                    <i class="material-icons" style="cursor: pointer;">&#xE872;</i>
                </a>
            </td>
            <td>
                <input class="fixedCol3" type="text" value="@item.Name" />
            </td>
            <td>
                <select name="Roles" id="Roles">
                    @foreach (var dow in item.Roles)
                    {
                        if (@item.RoleId == @dow.Id)
                        {
                        <option id="@dow.Id" value="@dow.Value" selected>@dow.Value</option>
                        }
                        else
                        {
                        <option id="@dow.Id" value="@dow.Value">@dow.Value</option>
                        }
                    }
                </select>
            </td>
            <td>
                <input type="text" value="@item.Email"  />
            </td>
            <td>
                <input type="text" value="@item.LoginId"  />
            </td>
            <td>
                <input type="text" value="@item.Password"  />
            </td>
            <td>
                <select name="Statuses" id="Statuses">
                    @foreach (var dow in item.Statuses)
                    {
                        if (@item.Status == @dow.Value)
                        {
                        <option value="@dow.Value" selected>@dow.Value</option>
                        }
                        else
                        {
                        <option value="@dow.Value">@dow.Value</option>
                        }
                    }
                </select>
            </td>
            <td>
                <input type="text" value="@item.POSCounter"  />
            </td>
            <td>
                <input type="text" value="@item.Department" />
            </td>
            <td>
                <input type="text" value="@item.Manager" />
            </td>
            <td>
                <input type="checkbox"  @(item.CompanyAdmin ? "checked='checked'" : "") value="@item.CompanyAdmin" />
            </td>
            <td>
                <input type="text" value="@item.EmpStartDate"  />
            </td>
            <td>
                <input type="text" value="@item.EmpEndDate" />
            </td>
            <td>
                <input type="text" value="@item.EmpEndReason"  />
            </td>
            <td>
                <input type="text" value="@item.PaswardChangeDate"  disabled/>
            </td>
            <td>
                <input type="text" value="@item.InvalidAttempts"  disabled/>
            </td>
            <td>
                <input type="text" value="@item.LastLoginTime"  disabled/>
            </td>
            <td>
                <input type="text" value="@item.LastLogoutTime"  disabled/>
            </td>
            <td>
                <input type="text" value="@item.CreationDate"  disabled/>
            </td>
            <td>
                <input type="text" value="@item.CreatedBy"  disabled/>
            </td>
            <td>
                <input type="text" value="@item.LastUpdatedBy"  disabled/>
            </td>
            <td>
                <input type="text" value="@item.LastUpdatedDate"  disabled/>
            </td>
        </tr>  
    }
</table>

<div class="action">

    <button class="btn btn-primary btn-md" role="button" onclick="SaveUsers()">Save</button>
    <button class="btn btn-primary btn-md" role="button" id="addRow">Add User</button>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#basicExampleModal" onclick="EditUser()">
        New
    </button>
    <button class="btn btn-primary btn-md" role="button" onclick="history.back();"  id="back">Back</button>
    <button class="btn btn-primary btn-md" role="button" onclick="location.href='/'">Close</button>


</div>
<script>
    $(document).ready(function () {
        var table = $('#marbleTable').DataTable({
            scrollY: "400px",
            scrollX: true,
            scrollCollapse: true,
            editable: true,
            stateSave: true,
            // paging: true,
            bPaginate: false,
            bInfo: false,
            bFilter: false,
            bSort: false,
            "createdRow": function (row, data, index) {
                $('td', row).addClass('tblRow');
            },
            rowCallback: function (row, data) {
                var element = $('td', row);
                element.on("change", function (e) {
                    UpdatedList($(this).parent().index());
                });
            },
            //order: [[ 0, "desc" ]],
            fixedColumns: {
                leftColumns: 3
            }
        });
        $('#marbleTable tbody').on('click', 'tr', function () {
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
            }
            else {
                table.$('tr.selected').removeClass('selected');
                $(this).addClass('selected');
            }
        });
        $('#addRow').on('click', function () {
            var fixedcolumn1values = $('.DTFC_Cloned lable.fixedCol1');
            var fixedcolumn3values = $('.DTFC_Cloned input.fixedCol3');

            var rolesOptions = '';
              @foreach (var dow in ViewBag.users[0].Roles)
              {
                 @: rolesOptions = rolesOptions + '<option id="@dow.Id" value="" >@dow.Value</option>';
              }
            rolesOptions = rolesOptions + '</select>';
            var statusListOptions = '';
              @foreach (var dow in ViewBag.users[0].Statuses)
              {
                 @: statusListOptions = statusListOptions + '<option id="@dow.Id" value="" >@dow.Value</option>';
              }
            statusListOptions = statusListOptions + '</select>';
            table.row.add([
                '<lable class="fixedCol1"></lable>',
                '',
                '<input class="fixedCol3" type="text" value="" />',
                '<select name="roles" id="roles">' + rolesOptions,
                '<input type="text" value="" />',
                '<input type="text" value="" />',
                '<input type="text" value="" />',
                '<select name="statuses" id="statuses">' + statusListOptions,
                '<input type="text" value="" />',
                '<input type="text" value="" />',
                '<input type="text" value="" />',
                '<input type="checkbox" />',
                '<input type="text" value="" />',
                '<input type="text" value="" />',
                '<input type="text" value="" />',
                '<input type="text" value="" disabled/>',
                '<input type="text" value="" disabled/>',
                '<input type="text" value="" disabled/>',
                '<input type="text" value="" disabled/>',
                '<input type="text" value="" disabled/>',
                '<input type="text" value="" disabled/>',
                '<input type="text" value="" disabled/>',
                '<input type="text" value="" disabled/>',
            ]).draw(false);

            for (var i = 0, j = fixedcolumn1values.length; i < j; i++) {
                $('.DTFC_Cloned lable.fixedCol1')[i].innerHTML = fixedcolumn1values[i].innerHTML;
            }
            for (var i = 0, j = fixedcolumn3values.length; i < j; i++) {
                $('.DTFC_Cloned input.fixedCol3')[i].value = fixedcolumn3values[i].value;
            }
        });
        $(".tblRow").on("change", function (e) { UpdatedList($(this).parent().index()); });
    });
    function SaveUsers() {
        if (updatedArray.length > 0) {
            var items = [];
            var table = document.getElementById('marbleTable');
            var fixedcolumn1 = $('.DTFC_Cloned lable.fixedCol1');
            var fixedcolumn3 = $('.DTFC_Cloned input.fixedCol3');

            for (var r = 0, n = table.rows.length; r < n; r++) {
                if (updatedArray.includes(r)) {
                    var rowIndex = r + 1;
                    var selectedRoleIndex = table.rows[rowIndex].cells[3].children[0].options["selectedIndex"];
                    var selectedStatusIndex = table.rows[rowIndex].cells[7].children[0].options["selectedIndex"];

                    items.push({
                        Id: fixedcolumn1[r].innerHTML,
                        Name: fixedcolumn3[r].value,
                        RoleId: table.rows[rowIndex].cells[3].children[0].options[selectedRoleIndex].id,
                        Email: table.rows[rowIndex].cells[4].children[0].value,
                        LoginId: table.rows[rowIndex].cells[5].children[0].value,
                        Password: table.rows[rowIndex].cells[6].children[0].value,
                        Status: table.rows[rowIndex].cells[7].children[0].options[selectedStatusIndex].innerText,
                        POSCounter: table.rows[rowIndex].cells[8].children[0].value,
                        Department: table.rows[rowIndex].cells[9].children[0].value,
                        Manager: table.rows[rowIndex].cells[10].children[0].value,
                        CompanyAdmin: table.rows[rowIndex].cells[11].children[0].checked,
                        EmpStartDate: table.rows[rowIndex].cells[12].children[0].value,
                        EmpEndDate: table.rows[rowIndex].cells[13].children[0].value,
                        EmpEnsReason: table.rows[rowIndex].cells[14].children[0].value
                    });
                }
            }
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '@Url.Action("InsertOrUpdateUsers", "SiteSetup")',
                data: JSON.stringify({ users: items }),
                dataType: "json",
                success: function (returndata) {
                    if (returndata.ok) {
                        alert("Data Saved")
                    }
                    else {
                        //this is an error from the server
                        window.alert(' error : ' + returndata.message);
                    }

                }
            });
        }
    }
    var updatedArray = [];
    function UpdatedList(rowIndex) {
        if (!updatedArray.includes(rowIndex)) {
            updatedArray.push(rowIndex);
        }
    }
    function EditUser(id) {
        $('#myModal').modal('show');
        $('#modelBody').css({
            'left': '-40%',
            'width': 850
        });
        if (id != 0) {
            $('#modelBody').load('/SiteSetup/EditUser', { "id": id });
            $('.modal-title').text('Edit Product');
        } else {
            $('#modelbody').load('/SiteSetup/EditUser');
            $('.modal-title').text('New User');
        }
    }
    function DeleteUser(id) {
        if (confirm('Are you sure you want to delete this from database?')) {
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: '@Url.Action("DeleteUser", "User")',
                data: { Id: id },
                dataType: "json",
                success: function (data) {
                    location.reload();
                },
                error: function (e) {
                    alert(e);
                }
            });
        }

    }
</script>
